/**
 * Copyright (c) 2005-2010 springside.org.cn
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * 
 * $Id: Page.java 1183 2010-08-28 08:05:49Z calvinxiu $
 */
package com.kevin.utility.common;

import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang.StringUtils;



/**
 * 
* ********************************************
* ClassName: Page
* Description: 与具体ORM实现无关的分页参数及查询结果封装.
* author:   jason
* date:     Jun 30, 2013 9:47:23 PM
* version:  v1.0
* ********************************************
 */
public class Page<T> {
	
	public static final String UTF8 = "UTF-8";
	//-- 公共变量 --//
	public static final String ASC = "asc";
	public static final String DESC = "desc";

	//-- 分页参数 --//
	protected int pageNo = 1;
	protected int pageSize = 20;
	private long totalPage=1;
	protected String orderBy = null;
	protected String order = null;
	protected boolean autoCount = true;

	protected int startNo = 0;
	protected int endNo = 0;
	//-- 返回结果 --//
	protected List<T> result = new ArrayList<T>();
	protected long totalCount = 0;
	//查询参数
	private Map<String,String> params = new HashMap<String,String>(); 

	//-- 构造函数 --//
	public Page() {
	}

	public Page(HttpServletRequest request){
		
		this.params = getAllParams(false, request);
		try{
			this.pageNo = Integer.valueOf(params.get("page").toString());
		}catch(Exception e){
			this.pageNo = 1;
		}
		try{
			this.pageSize = Integer.valueOf(params.get("pageSize").toString());
		}catch(Exception e){
			this.pageSize = 20;
		}
	}
	public Page(int pageSize) {
		this.pageSize = pageSize;
	}

	//-- 分页参数访问函数 --//
	/**
	 * 获得当前页的页号,序号从1开始,默认为1.
	 */
	public int getPageNo() {
		return pageNo;
	}

	/**
	 * 设置当前页的页号,序号从1开始,低于1时自动调整为1.
	 */
	public void setPageNo(final int pageNo) {
		this.pageNo = pageNo;
	}

	/**
	 * 返回Page对象自身的setPageNo函数,可用于连续设置。
	 */
	public Page<T> pageNo(final int thePageNo) {
		setPageNo(thePageNo);
		return this;
	}

	/**
	 * 获得每页的记录数量, 默认为-1.
	 */
	public int getPageSize() {
		return pageSize;
	}

	/**
	 * 设置每页的记录数量.
	 */
	public void setPageSize(final int pageSize) {
		this.pageSize = pageSize;
	}

	/**
	 * 返回Page对象自身的setPageSize函数,可用于连续设置。
	 */
	public Page<T> pageSize(final int thePageSize) {
		setPageSize(thePageSize);
		return this;
	}

	/**
	 * 根据pageNo和pageSize计算当前页第一条记录在总结果集中的位置,序号从1开始.
	 */
	public int getFirst() {
		return ((pageNo - 1) * pageSize) + 1;
	}

	/**
	 * 获得排序字段,无默认值. 多个排序字段时用','分隔.
	 */
	public String getOrderBy() {
		return orderBy;
	}

	/**
	 * 设置排序字段,多个排序字段时用','分隔.
	 */
	public void setOrderBy(final String orderBy) {
		this.orderBy = orderBy;
	}

	/**
	 * 返回Page对象自身的setOrderBy函数,可用于连续设置。
	 */
	public Page<T> orderBy(final String theOrderBy) {
		setOrderBy(theOrderBy);
		return this;
	}

	/**
	 * 获得排序方向, 无默认值.
	 */
	public String getOrder() {
		return order;
	}

	/**
	 * 设置排序方式向.
	 * 
	 * @param order 可选值为desc或asc,多个排序字段时用','分隔.
	 */
	public void setOrder(final String order) {
		String lowcaseOrder = StringUtils.lowerCase(order);

		//检查order字符串的合法值
		String[] orders = StringUtils.split(lowcaseOrder, ',');
		for (String orderStr : orders) {
			if (!StringUtils.equals(DESC, orderStr) && !StringUtils.equals(ASC, orderStr)) {
				throw new IllegalArgumentException("排序方向" + orderStr + "不是合法值");
			}
		}

		this.order = lowcaseOrder;
	}

	/**
	 * 返回Page对象自身的setOrder函数,可用于连续设置。
	 */
	public Page<T> order(final String theOrder) {
		setOrder(theOrder);
		return this;
	}

	/**
	 * 是否已设置排序字段,无默认值.
	 */
	public boolean isOrderBySetted() {
		return (StringUtils.isNotBlank(orderBy) && StringUtils.isNotBlank(order));
	}

	/**
	 * 获得查询对象时是否先自动执行count查询获取总记录数, 默认为true.
	 */
	public boolean isAutoCount() {
		return autoCount;
	}

	/**
	 * 设置查询对象时是否自动先执行count查询获取总记录数.
	 */
	public void setAutoCount(final boolean autoCount) {
		this.autoCount = autoCount;
	}

	/**
	 * 返回Page对象自身的setAutoCount函数,可用于连续设置。
	 */
	public Page<T> autoCount(final boolean theAutoCount) {
		setAutoCount(theAutoCount);
		return this;
	}

	//-- 访问查询结果函数 --//

	/**
	 * 获得页内的记录列表.
	 */
	public List<T> getResult() {
		return result;
	}

	/**
	 * 设置页内的记录列表.
	 */
	public void setResult(final List<T> result) {
		this.result = result;
	}

	/**
	 * 获得总记录数, 默认值为-1.
	 */
	public Long getTotalCount() {
		return totalCount;
	}

	/**
	 * 设置总记录数.
	 */
	public void setTotalCount(final long totalCount) {
		this.totalCount = totalCount;
		totalPage = getTotalPages();
				
	}

	/**
	 * 根据pageSize与totalCount计算总页数, 默认值为-1.
	 */
	public long getTotalPages() {
		if (totalCount < 0) {
			return -1;
		}

		long count = totalCount / pageSize;
		if (totalCount % pageSize > 0) {
			count++;
		}
		if(count == 0l){
			count = 1l;
		}
		return count;
	}

	/**
	 * 是否还有下一页.
	 */
	public boolean isHasNext() {
		return (pageNo + 1 <= getTotalPages());
	}

	/**
	 * 取得下页的页号, 序号从1开始.
	 * 当前页为尾页时仍返回尾页序号.
	 */
	public int getNextPage() {
		if (isHasNext()) {
			return pageNo + 1;
		} else {
			return pageNo;
		}
	}

	/**
	 * 是否还有上一页.
	 */
	public boolean isHasPre() {
		return (pageNo - 1 >= 1);
	}

	/**
	 * 取得上页的页号, 序号从1开始.
	 * 当前页为首页时返回首页序号.
	 */
	public int getPrePage() {
		if (isHasPre()) {
			return pageNo - 1;
		} else {
			return pageNo;
		}
	}

	public Map<String, String> getParams() {
		return params;
	}

	public void setParams(Map<String, String> params) {
		this.params = params;
	}
	
	public static Page getPage(HttpServletRequest request) {
		Map<String, String> params = getAllParams(false, request);
		Page page = new Page();
		page.setPageSize(20);
		page.setParams(params);
		if (getLong(request,"rows") != null) {
			page.setPageSize(getLong(request,"rows").intValue());
		}
		if (getLong(request,"page") != null) {
			page.setPageNo(getLong(request,"page").intValue());
		}
		if (getLong(request,"pagesize") != null) {
			page.setPageSize(getLong(request,"pagesize").intValue());
		}
		// 取得排序参数
		String sort = getString(request,"sortorder");// asc,desc
		String order = getString(request,"sortname");// 		
		if (StringUtils.isNotEmpty(sort)) {
			page.setOrder(sort);
		}
		if (StringUtils.isNotEmpty(order)) {
			page.orderBy(order);
		}
		return page;
	}
 
	public static Integer getInt(HttpServletRequest request, String key){
		String parameter = request.getParameter(key);
		if(StringUtils.isNotBlank(parameter)){
			return Integer.valueOf(parameter);
		}
		return null;
	}
	
	public static String getString(HttpServletRequest request, String key){
		String parameter = request.getParameter(key);
		return parameter;
	}
	
	public static Long getLong(HttpServletRequest request, String key){
		String parameter = request.getParameter(key);
		if(StringUtils.isNotBlank(parameter)){
			return Long.valueOf(parameter);
		}
		return null;
	}
	
	public static Map<String, String> getAllParams(boolean isAllowEmpty,HttpServletRequest request) {
		Enumeration<String> rp = request.getParameterNames();
		Map<String, String> data = new HashMap<String, String>();
		while (rp.hasMoreElements()) {
			
			try {
				String key = rp.nextElement();
				String value = request.getParameter(key);
				
				if (isAllowEmpty) {
					if (value == null || value.equals("")) {
						data.put(key, null);
					} else {
						data.put(key, URLDecoder.decode(value,UTF8));
					}
				} else if (value != null && !value.equals("")) {
					data.put(key, URLDecoder.decode(value,UTF8));
				}
			} catch (UnsupportedEncodingException e) {
				e.printStackTrace();
			}
		}
		return data;
	}

	public long getTotalPage() {
		return totalPage;
	}

	public void setTotalPage(long totalPage) {
		this.totalPage = totalPage;
	}

	public int getStartNo() {
		return startNo;
	}

	public void setStartNo(int startNo) {
		this.startNo = startNo;
	}

	public int getEndNo() {
		return endNo;
	}

	public void setEndNo(int endNo) {
		this.endNo = endNo;
	}
	
	
}
